<?php

namespace app\backend\controller;

use app\common\RootController;
use app\backend\service\AuthService;
use app\backend\service\MenuService;

class Backend extends RootController
{
    /**
     * 初始化
     */
    protected function initialize()
    {
        in_array(app('http')->getName(), ['backend']) && $this->menuSelect();
    }

    /**
     * 菜单选择
     */
    protected function menuSelect()
    {
        $currentUri = [app('http')->getName(), $this->request->controller(), $this->request->action()];
        $currentUrl = strtolower(join('/', $currentUri));
        $mainPage = in_array($currentUri[2], ['index', 'console']);
        // 初始化菜单
        if (!in_array($currentUrl, ['backend/login/index', 'backend/nostatecode/imgcode'])) {
            // 菜单列表
            $menuList = app()->make(MenuService::class)->lists();
            // 数据处理
            empty($menuList) || array_walk($menuList, function (&$menus) use ($currentUrl, &$homeUrl, &$pageTitle) {
                $select = 0;
                // 循环子菜单
                foreach ($menus['subMenu'] as &$menu) {
                    if (strtolower($menu['url']) == $currentUrl) {
                        $select = 1;
                        $menu['select'] = 1;// 选中子菜单
                        $pageTitle = $menu['title'];
                        $homeUrl = url($menu['url']);
                    }
                }
                // 选中主菜单
                $menus['select'] = $select;
            });
            // 如果未命中
            if (empty($homeUrl) && $mainPage) {
                header("Location: " . url($menuList[0]['subMenu'][0]['url']), true, 302);
            }
            // 模板赋值
            $this->assign('mainPage', $mainPage);
            $this->assign('menuList', $menuList);
            // 缓存
            $cacheName = 'actionBtn' . adminInfo('id');
            // 操作按钮
            if (in_array($currentUri[2], ['index'])) {
                $actionBtn = app()->make(AuthService::class)->actionBtn($currentUri);
                cache($cacheName, json_encode($actionBtn), 144000);
            }
            $this->assign('actionBtn', json_decode(cache($cacheName) ?: '[]', true));
        }
        // 页面标题
        $this->assign('pageTitle', $pageTitle ?? ($menuList[0]['subMenu'][0]['title'] ?? env('app_name')));
    }
}